package cn.silver.module.system.service.impl;


import cn.silver.framework.core.config.SilverConfig;
import cn.silver.framework.core.enums.SystemStatusEnums;
import cn.silver.framework.core.utils.CommonUtils;
import cn.silver.framework.core.utils.MapstructUtils;
import cn.silver.framework.mybatis.service.impl.BaseServiceImpl;
import cn.silver.module.system.bean.AvatarBean;
import cn.silver.module.system.domain.SysUserAvatar;
import cn.silver.module.system.mapper.SysUserAvatarMapper;
import cn.silver.module.system.param.AvatarParam;
import cn.silver.module.system.service.ISysUserAvatarService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

/**
 * @author zhouxiaobo
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserAvatarServiceImpl extends BaseServiceImpl<SysUserAvatarMapper, SysUserAvatar, AvatarParam, AvatarBean>
        implements ISysUserAvatarService {

    private final SilverConfig config;

    @Override
    public String upload(String userId, MultipartFile file) {
        SysUserAvatar sysUserAvatar = new SysUserAvatar();
        sysUserAvatar.preInsert();
        String biz = StringUtils.isNotBlank(userId) ? userId : "temp";
        String path = CommonUtils.uploadLocal(file, biz, config.getAvatarPath());
        sysUserAvatar.setUserId(userId);
        sysUserAvatar.setFilePath(config.getAvatar() + "/" + path);
        sysUserAvatar.setFileName(path.substring(path.lastIndexOf("/") + 1));
        sysUserAvatar.setUploadTime(new Date());
        sysUserAvatar.setStatus(SystemStatusEnums.NORMAL.getCode());
        sysUserAvatar.preInsert();
        this.baseMapper.insert(sysUserAvatar);
        return sysUserAvatar.getId();
    }

    @Override
    public String executeAvator(String userId, String avatarId) {
        AvatarBean bean = this.selectById(avatarId);
        if (bean == null) {
            return null;
        }
        SysUserAvatar avatar = MapstructUtils.convert(bean, SysUserAvatar.class);
        if (StringUtils.isBlank(avatar.getUserId()) || !userId.equals(avatar.getUserId())) {
            String newPath = userId + File.separator + avatar.getFileName();
            CommonUtils.moveFile(config.getProfile() + File.separator + avatar.getFilePath(),
                    config.getAvatarPath() + File.separator + newPath);
            avatar.setFilePath(config.getAvatar() + "/" + newPath);
            avatar.setUserId(userId);
            this.baseMapper.updateById(avatar);
        }
        return avatar.getFilePath();
    }

}
